#include<iostream>
#include<signal.h>
#include"../comm/httplib.h"
#include"oj_control.hpp"

using namespace httplib;
using namespace ns_control;

static Control* ctrl_ptr = nullptr;

void recovery(int signo)
{
    ctrl_ptr->RecoveryMachine();
}

int main()
{
    signal(SIGQUIT, recovery);

    Server svr;
    Control ctrl;
    ctrl_ptr = &ctrl;

    //获取所有题目列表
    svr.Get("/all_questions",[&ctrl](const Request& req, Response& resp){
        //返回一张包含所有题目的网页
        std::string html;
        ctrl.AllQuestions(&html);

        resp.set_content(html,"text/html; charset=utf-8");
    });

    //用户根据题目编号，获取题目内容
    //R：Raw string，原始字符串。 
    //\d+：正则表达式；\d：匹配字符，+匹配一个或者多个字符
    //req.matches[1]：获取正则表达式的值
    svr.Get(R"(/question/(\d+))",[&ctrl](const Request& req, Response& resp){
        std::string number = req.matches[1];
        //返回一张包含指定题目的wangye
        std::string html;
        ctrl.Question(number,&html);

        resp.set_content(html,"text/html; charset=utf-8");
    });


    //用户提交代码，使用我们的判题功能(1.每道题的测试用例 2.compile_and_run)
    svr.Post(R"(/judge/(\d+))",[&ctrl](const Request& req, Response& resp){
        std::string number = req.matches[1];
        std::string result_json;
        ctrl.Judge(number, req.body, &result_json);
        resp.set_content(result_json, "application/json;charset=utf-8");
        //resp.set_content("这是要判断的一道题" + number,"text/plain; charset=utf-8");
    });

    
    //主页
    svr.set_base_dir("./wwwroot");

    svr.listen("0.0.0.0",8080);
    return 0;
}